package com.edu.imau;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

@WebServlet("/Login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        String remember = req.getParameter("remember");
        boolean T=false;
        Connection connection = ConnectionManager.getConnection();
        try {
            Statement statement = connection.createStatement();
            String sql = "select * from usermanager order by id desc";
            ResultSet resultSet = statement.executeQuery(sql);
            while ((resultSet.next())){
                if(username.equals(resultSet.getString("name"))&&password.equals(resultSet.getString("code")))
                {
                    T=true;
                    break;
                }
            }
            if(T){
                HttpSession session = req.getSession();
                session.setAttribute("login_status","OK");

                if ("on".equals(remember)) {
                    session.setMaxInactiveInterval(60*60*24*3);
                    Cookie cookie = new Cookie("JSESSIONID", session.getId());
                    resp.addCookie(cookie);
                }
                resp.sendRedirect("main.jsp");
            }
            else{
                String error_msg = "username or password is wrong!";
                // 把数据保存到 request对象中， 并转发request到目标servlet(JSP)
                req.setAttribute("msg", error_msg);
                req.getRequestDispatcher("index.jsp").forward(req, resp);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
